package com.dwjm.exam.stu_login;

import com.dwjm.exam.pojo.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/slogin")
public class StudentLoginHandler extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");

        String account = req.getParameter("account");
        String password = req.getParameter("password");

        StudentDaoImpl studentDao = new StudentDaoImpl();
        Student student = studentDao.Login(account, password);

        PrintWriter out = resp.getWriter();
        if(student != null){
            HttpSession session = req.getSession();
            session.setAttribute("loggedInStudent", student);
            session.setAttribute("userType", "student");
            session.setAttribute("studentId", student.getStudentId());
            // 登录成功，返回成功状态和用户信息
            out.write("{\"code\":200,\"msg\":\"登录成功\",\"data\":{\"id\":" + student.getStudentId() +
                    ",\"account\":\"" + student.getUserName() + "\"}}");
        } else {
            // 登录失败，返回失败状态和信息
            out.write("{\"code\":400,\"msg\":\"账号或密码错误\"}");
        }
        out.flush();
        out.close();
    }
}
